#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QFileDialog>
#include <QDir>
#include <QMessageBox>
#include <QDesktopServices>

MainWindow::MainWindow(QWidget* parent) : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    networkManager = new QNetworkAccessManager(this);

    // “默认路径”按钮
    connect(ui->btnDefaultPath, &QPushButton::clicked, this, [this]() {
        QString curPath = QDir::currentPath();
        QDir dir(curPath);
        QString sub = "temp";
        dir.mkdir(sub);
        ui->editPath->setText(curPath + '/' + sub + '/');
    });

    // “下载”按钮，开始下载
    connect(ui->btnDownload, &QPushButton::clicked, this, [this]() {
        QString urlSpec = ui->editURL->text().trimmed();
        if (urlSpec.isEmpty())
        {
            QMessageBox::information(this, "错误", "请指定需要下载的URL");
            qDebug() << "URL 为空";
            return;
        }
        // URL
        QUrl newUrl = QUrl::fromUserInput(urlSpec);
        if (!newUrl.isValid())
        {
            QMessageBox::information(this, "错误", "URL无效");
            qDebug() << "URL 无效";
            return;
        }
        // 临时目录
        QString tempDir = ui->editPath->text().trimmed();
        if (tempDir.isEmpty())
        {
            qDebug() << "路径无效";
            QMessageBox::information(this, "错误", "URL无效");
            return;
        }
        // 文件名
        QString fullFileName = tempDir + newUrl.fileName();
        if (QFile::exists(fullFileName))
        {
            QFile::remove(fullFileName);
        }
        // 创建临时文件
        downloadFile = new QFile(fullFileName);
        if (!downloadFile->open(QIODevice::WriteOnly))
        {
            QMessageBox::information(this, "错误", "文件打开失败");
            qDebug() << "文件打开失败";
            return;
        }
        //发送网络请求、创建网络响应
        reply = networkManager->get(QNetworkRequest(newUrl));//有的URL涉及重定向什么的，我的代码无法正常下载

        // QNetworkRequest request(newUrl);

        // // 👇 使用 RedirectPolicyAttribute 替代 FollowRedirectsAttribute
        // request.setAttribute(QNetworkRequest::RedirectPolicyAttribute,
        //                      QNetworkRequest::NoLessSafeRedirectPolicy);
        // reply = networkManager->get(request);

        connect(reply, &QNetworkReply::readyRead, this, &MainWindow::do_readyRead);
        connect(reply, &QNetworkReply::downloadProgress, this, &MainWindow::do_downloadProgress);
        connect(reply, &QNetworkReply::finished, this, &MainWindow::do_finished);

        ui->btnDownload->setEnabled(false);
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::do_readyRead()
{
    downloadFile->write(reply->readAll());
}

void MainWindow::do_finished()
{
    QFileInfo fileInfo(downloadFile->fileName()); // 获取下载的文件的文件名
    downloadFile->close();
    delete downloadFile;  // 删除临时文件对象
    reply->deleteLater(); // 由主事件循环删除此对象

    if (ui->chkBoxOpen->isChecked())
    {
        QDesktopServices::openUrl(QUrl::fromLocalFile(fileInfo.absoluteFilePath())); // 打开下载的文件
    }

    ui->btnDownload->setEnabled(true);

    qDebug()<<"下载完成";
}

void MainWindow::do_downloadProgress(int64_t bytesReceived, int64_t bytesTotal)
{
    ui->progressBar->setMaximum(bytesTotal);
    ui->progressBar->setValue(bytesReceived);
}
